<template>
  <div class="app-container">
    <!-- 搜索 -->
    <!-- //label-width="68px" -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="设备类型" prop="saleNel">
        <el-select
        v-model="queryParams.saleNel"
        placeholder="请选择设备类型"
        ref="queryForm"
        clearable
        style="width: 100%"
      >
        <el-option
          v-for="item in equType"
          :label="item.label"
          :key="item.value"
          :value="item.value"
        >
        </el-option>
      </el-select>
      </el-form-item>
      <el-form-item label="设备sn码" prop="equipmentSn">
        <el-input
          v-model="queryParams.equipmentSn"
          placeholder="请输入设备sn码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['kenuo:equ:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['kenuo:equ:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['kenuo:equ:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['kenuo:equ:export']">导出</el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="equList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="编码" align="center" prop="id" /> -->
      <el-table-column label="设备sn码" align="center" prop="equipmentSn" />
      <el-table-column label="设备型号" align="center" prop="equipmentModel"></el-table-column>
      <el-table-column label="设备类型" align="center" prop="saleNel">
        <template slot-scope="scope">
          {{ scope.row.saleNel == 0 ? "医用" : scope.row.saleNel == 1? "家医两用":"家用"  }}
        </template>
      </el-table-column>
<!--      <el-table-column label="绑定状态" align="center" prop="boundStatus">
        <template slot-scope="scope">
          {{ scope.row.boundStatus == 1 ? "未绑定" : "已绑定" }}
        </template>
      </el-table-column>-->
<!--      <el-table-column label="绑定客户" align="center" prop="boundName" />-->
<!--      <el-table-column label="客户账号" align="center" prop="boundPhone" />
      <el-table-column label="绑定时间" align="center" prop="boundTime" />-->
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['kenuo:equ:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['kenuo:equ:remove']"
            >删除</el-button
          >
          <!-- 1未绑定 2绑定 -->
<!--          <el-button
            v-if="scope.row.boundStatus == 2"
            size="mini"
            type="text"
            icon="el-icon-connection"
            @click="goBound(scope.row)"
            >解绑</el-button
          >-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      v-if="open"
      width="650px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item  label="设备SN编码" prop="equipmentSn">
            <el-input
              :disabled="disab"
              v-model="form.equipmentSn"
              placeholder="设备SN编码"
            />
          </el-form-item>

          <el-form-item label="设备型号" prop="equipmentModel">
            <el-select
              v-model="form.equipmentModel"
              placeholder="请选择设备型号"
              ref="xsCompany"
              @change="changeModelForm"
              style="width: 100%"
            >
              <el-option
                v-for="item in modelList"
                :label="item.dictLabel"
                :key="item.dictValue"
                :value="item.dictValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型">
            <el-radio-group v-model="form.saleNel">
              <el-radio label="0">医用</el-radio>
              <el-radio label="1">家医两用</el-radio>
              <el-radio label="2">家用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="销售机构" prop="xsUserId">
            <el-select
              v-model="form.xsUserId"
              placeholder="请选择经销商"
              ref="xsCompany"
              @change="changeForm"
              style="width: 100%"
            >
              <el-option
                v-for="item in companyList"
                :label="item.userName"
                :key="item.userId"
                :value="item.userId"
              >
              </el-option>
            </el-select>
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的设备数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listEqu,
  getEqu,
  delEqu,
  addEqu,
  getListSystemData,
  updateEqu,
  deleteEqueUser,
  removeEquUser

} from "@/api/kenuo/equ";
import { getUserListByRole } from "@/api/system/role";
import { getToken } from "@/utils/auth";
export default {
  name: "Equ",
  data() {
    return {
      disab:false,
      equType:[
        {
          label:'医用',
          value:"0"
        },
        {
          label:'家医两用',
          value:"1"
        },
        {
          label:'家用',
          value:"2"
        }
      ],
      modelList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      equList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentSn: null,
        equipmentModel: null,
        version: null,
        xsUserId: null,
        xsName: null,
        boundStatus: null,
        boundId: null,
        boundName: null,
        equipmentName: null,
        boundPhone: null,
        therapyNum: null,
        boundTime: null,
        unboundTime: null,
        isLease: null,
        leaseCreateTime: null,
        leaseEndTime: null,
        saleNel: null,
        des:null
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/kenuo/equ/importData",
      },
      // 设备用户列表
      userList: [],
      // 经销商列表
      companyList: [],
      // 表单参数
      currentCompany: "",
      form: {
        id: null,
        equipmentSn: null,
        equipmentModel: null,
        version: null,
        xsUserId: null,
        saleNel:"0",
        boundStatus: null,
        isLease: null,
        equipmentName: null,
      },
      // 表单校验
      rules: {
        equipmentSn: [
          {
            required: true,
            message: "设备sn码不能为空",
            trigger: "blur",
          },
        ],

        equipmentModel: [
          {
            required: true,
            message: "设备型号不能为空",
            trigger: "blur",
          },
        ],

        xsUserId: [
          {
            required: true,
            message: "销售机构不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getSystem();
    this. getUserList();
  },
  mounted() {

  },
  methods: {
    // 获取经销商列表
    getUserList() {
      getUserListByRole({
        roleName: '经销商'
      }).then(response => {
        this.companyList = response.data;
      });
    },
    // 获取设备型号列表
    getSystem() {
      let data = {
       dictType:"equ_type"
      }
      getListSystemData(data).then((response) => {
        this.modelList = response.rows;
      });
    },
// 获取设备型号
    /** 查询设备列表 */
    getList() {
      this.loading = true;
      listEqu(this.queryParams).then((response) => {
        this.equList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        equipmentSn: null,
        equipmentModel: null,
        version: null,
        xsUserId: null,
        saleNel:"0",
        boundStatus: null,
        isLease: null,
        equipmentName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.disab = false;
      this.title = "添加设备";
    },
    // 切换公司名
    changeForm(value) {
      this.$forceUpdate();
      this.companyList.map((item) => {
        if (item.userId == value) {
          this.currentCompany = item.userName;
        }
      });
    },
    changeModelForm(v){
      this.$forceUpdate();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.disab = true;
      const id = row.id || this.ids;
      getEqu(id).then((response) => {
        this.currentCompany = response.data.xsName;
        this.form = response.data;
        this.form.xsUserId = Number(this.form.xsUserId);
        this.form.boundStatus=this.form.boundStatus+"";
        this.form.isLease=this.form.isLease+"";
        this.form.saleNel = String(response.data.saleNel);
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.xsName = this.currentCompany;
          if (this.form.id != null) {
            updateEqu(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.boundStatus = 1;
            addEqu(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          return delEqu(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "kenuo/equ/export",
        {
          ...this.queryParams,
        },
        `equ_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "kenuo/equ/importTemplate",
        {},
        '设备模板'+`${new Date().getTime()}.xls`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        {
          dangerouslyUseHTMLString: true,
        }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    //绑定
    goBound(row) {
      if (row.boundStatus == 2) {
        //已绑定--解绑操作
        if (!row.boundPhone) {
          this.$modal.msgError("设备绑定手机号不存在");
          return;
        }
        let obj = {
          tel: row.boundPhone,
          snCode: row.equipmentSn,
        };
        this.$modal
          .confirm("是否确认解绑？")
          .then(function () {
            return removeEquUser(obj);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("解绑成功");
          })
          .catch(() => {

          });
      }
    },
  },
};
</script>
<style >
input::-webkit-input-placeholder {
  font-size: 12px;
}
input::-moz-input-placeholder {
  font-size: 12px;
}
input::-ms-input-placeholder {
  font-size: 12px;
}
</style>
